package com.zxh.blog.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.request.RequestOptions
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.gyf.immersionbar.ImmersionBar
import com.zxh.blog.R
import com.zxh.blog.bean.ResponseJson
import com.zxh.blog.bean.UserInfo
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okio.IOException

class EditInfoActivity : AppCompatActivity() {

    // 返回按钮
    private lateinit var mBackBtn: ImageButton

    // 保存按钮
    private lateinit var mSave: TextView

    // 头像
    private lateinit var mAvatar: ImageView

    // 昵称
    private lateinit var mNickName: EditText

    // 邮箱
    private lateinit var mEmail: EditText

    // 性别
    private lateinit var mSex: EditText

    private lateinit var mSharedPreferences: SharedPreferences

    private val mJSON = "application/json".toMediaType()

    // SharedPreferences中的用户信息
    private lateinit var nickName: String
    private lateinit var avatarURL: String
    private lateinit var sex: String
    private lateinit var email: String
    private lateinit var id: String
    private lateinit var token: String


    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_edit_info)

        ImmersionBar.with(this)
            .statusBarColor(R.color.app_back)
            .statusBarDarkFont(true)
            .fitsSystemWindows(true)
            .init()

        // 初始化控件
        mBackBtn = findViewById(R.id.btn_back)
        mSave = findViewById(R.id.tv_save)
        mAvatar = findViewById(R.id.avatar)
        mNickName = findViewById(R.id.etNickname)
        mEmail = findViewById(R.id.etEmail)
        mSex = findViewById(R.id.etSex)

        // 读取用户信息
        mSharedPreferences = getSharedPreferences("user_info", Context.MODE_PRIVATE)
        nickName = mSharedPreferences.getString("nickName", "").toString()
        avatarURL = mSharedPreferences.getString("avatar", "").toString()
        sex = mSharedPreferences.getString("sex", "").toString()
        email = mSharedPreferences.getString("email", "").toString()
        id = mSharedPreferences.getString("id", "").toString()
        token = mSharedPreferences.getString("token", "").toString()

        // 给每个EditText赋初始值
        mNickName.setText(nickName)
        mEmail.setText(email)
        mSex.setText(sex)

        // 加载头像
        //imageView关闭硬件加速，降低内存消耗
        mAvatar.setLayerType(View.LAYER_TYPE_SOFTWARE, null)
        //降低图片质量
        val options = RequestOptions().format(DecodeFormat.PREFER_RGB_565)
        Glide.with(this)
            .load(avatarURL)
            .apply(options)
            .error(R.drawable.icon_user)
            .into(mAvatar)

        // 返回上一层
        mBackBtn.setOnClickListener {
            finish()
        }

        // 保存按钮
        mSave.setOnClickListener {
            // 更新后台数据
            updateRemoteData(this)
        }
    }

    /**
     *  更新后台数据库数据
     */
    private fun updateRemoteData(context: Context) {
        val client = OkHttpClient()
        val url = "http://43.140.201.43:7777/user/userInfo"
        val map = mutableMapOf<String, String>()
        var sexParams = ""
        map["avatar"] = avatarURL
        map["email"] = mEmail.text.toString()
        map["id"] = id
        map["nickName"] = mNickName.text.toString()
        sexParams = if (mSex.text.toString() == "男") {
            "0"
        } else {
            "1"
        }
        map["sex"] = sexParams
        map["head_start"] = "0"

        // 创建json格式的请求体
        val json = Gson().toJson(map)
        val requestBody = json.toRequestBody(mJSON)

        // 创建put请求
        val request = Request.Builder()
            .header("Token", token)
            .url(url)
            .put(requestBody)
            .build()

        var responseJson: ResponseJson<UserInfo>
        // 发送请求
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                // 请求失败处理
                e.printStackTrace()
            }

            override fun onResponse(call: Call, response: Response) {
                // 获取响应结果
                val responseBody = response.body?.string()
                // 处理响应结果
                if (response.isSuccessful) {
                    // 请求成功，处理登录成功逻辑
                    // 可以通过responseBody解析服务器返回的数据
                    if (responseBody != null) {
                        responseJson = parseJSONWithGSON(responseBody)
                        if (responseJson.code == 200) {
                            // 同步本地数据
                            updateSharedPreferencesData()
                            runOnUiThread {
                                Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show()
                            }
                            startActivity(Intent(context, UserInfoActivity::class.java))
                            finish()
                        } else {
                            runOnUiThread {
                                Toast.makeText(context, "服务器异常", Toast.LENGTH_SHORT).show()
                            }
                        }
                    }
                }
            }
        })
    }

    /**
     *  解析JSON
     */
    private fun parseJSONWithGSON(responseBody: String): ResponseJson<UserInfo> {
        val gson = Gson()
        val typeToken = object : TypeToken<ResponseJson<UserInfo>>() {}.type
        return gson.fromJson(responseBody, typeToken)
    }

    /**
     *  更新本地SharedPreferences数据
     */
    private fun updateSharedPreferencesData() {
        val editor = getSharedPreferences("user_info", Context.MODE_PRIVATE).edit()
        editor.putString("nickName", mNickName.text.toString())
        editor.putString("sex", mSex.text.toString())
        editor.putString("email", mEmail.text.toString())
        editor.apply()
    }
}